#import RPi.GPIO as GPIO
import time

colors=[0xff0000,0x00ff00,0x0000ff,0xffff00,0xff00ff,0x00ffff]
makerobo_R = 11
makerobo_G = 12
makerobo_B = 13

def makerobo_setup(Rpin,Gpin,Bpin):
    global pins
    global p_R,p_G,p_B
    pins = {'pin_R':Rpin,'pin_G':Gpin,'pin_B':Bpin}
    GPIO.setmode(GPIO.BOARD)  # 采用物理编号
    GPIO.setwarnings(False)  # 去除GPIO的警告
    for i in pins:  #i 表示的key  for i in pins.items():  i是 ('pin_R', 11) 整个元组
        GPIO.setup(pins[i], GPIO.OUT)  # 列表中都为out
        GPIO.output(pins[i], GPIO.LOW)  # pin都为low
    # 由于rgb每个led到达一定亮度 需要的电流不一样 所以设置频率不一样
    p_R = GPIO.PWM(pins['pin_R'], 2000)
    p_G = GPIO.PWM(pins['pin_G'], 1999)
    p_B = GPIO.PWM(pins['pin_B'], 5000)

    # 初始化占空比为0
    p_R.start(0)
    p_G.start(0)
    p_B.start(0)

# 比例缩放函数
def makerobo_pwm_map(x,in_min,in_max,out_min,out_max):
    return (x-in_min)*(out_max-out_min)/(in_max-in_min) + out_min


def makerobo_off():
    GPIO.setmode(GPIO.BOARD)  # 采用物理编号
    for i in pins:  # i 表示的key  for i in pins.items():  i是 ('pin_R', 11) 整个元组
        GPIO.setup(pins[i], GPIO.OUT)  # 列表中都为out
        GPIO.output(pins[i], GPIO.LOW)  # pin都为low

def makerobo_set_color(col):
    R_val = (col&0xff0000)>>16
    G_val = (col&0x00ff00)>>8
    B_val = (col&0x0000ff)>>0

    #把0-255范围同比例缩小到 0-100 之间
    R_val = makerobo_pwm_map(R_val,0,255,0,100)
    G_val = makerobo_pwm_map(G_val, 0, 255, 0, 100)
    B_val = makerobo_pwm_map(B_val, 0, 255, 0, 100)

    p_R.ChangeDutyCycle(R_val)
    p_G.ChangeDutyCycle(G_val)
    p_B.ChangeDutyCycle(G_val)

def loop():
    while True:
        for col in colors:
            makerobo_set_color(col)
            time.sleep(1)

def destroy():
    p_R.stop()
    p_G.stop()
    p_B.stop()
    GPIO.cleanup()  #释放资源


if __name__=='__main__':
    try:
        loop()
    except KeyboardInterrupt:   #按下 ctrl+c 释放资源
        destroy()